<template>
	<view class="address-edit-page">
		<view class="form-card">
			<view class="form-row">
				<view class="form-label">收货人</view>
				<input class="form-input" v-model="form.contacts" placeholder="请填写收货人姓名" />
			</view>
			<view class="form-row">
				<view class="form-label">手机号码</view>
				<input class="form-input" v-model="form.contactsPhone" placeholder="请填写收货人手机号" maxlength="11" />
			</view>
			<view class="form-row">
				<view class="form-label">所在地区</view>
				<input class="form-input" v-model="regionText" placeholder="请选择省市区" readonly @tap="chooseRegion" />
			</view>
			<view class="form-row">
				<view class="form-label">详细地址</view>
				<input class="form-input" v-model="form.detail" placeholder="请填写街道、楼牌号等" />
			</view>
			<view class="form-row">
				<view class="form-label">地址类型</view>
				<picker class="form-picker" :value="form.addressType || 0" :range="addressTypes" range-key="label" @change="onAddressTypeChange">
					<view class="picker-text">{{ addressTypes[form.addressType || 0].label }}</view>
				</picker>
			</view>
		</view>
		<view class="default-card">
			<view class="default-row">
				<view class="default-label">设置默认地址</view>
				<switch class="default-switch" :checked="form.isDefault" color="#2196f3" @change="e => form.isDefault = e.detail.value ? true : false" />
			</view>
			<view class="default-tip">提醒：下单会优先使用该地址</view>
		</view>
		<view class="save-btn-box">
			<button class="save-btn" @tap="saveAddress">保存</button>
		</view>

		<!-- 地图选择弹窗 -->
		<view class="map-popup" v-if="showMap">
			<view class="map-container">
				<view class="map-header">
					<text>选择位置</text>
					<text class="close-btn" @tap="closeMapPopup">×</text>
				</view>
				<view class="search-box">
					<input 
						class="search-input" 
						v-model="searchKeyword" 
						placeholder="搜索地址" 
						@confirm="searchLocation"
					/>
					<button class="search-btn" @tap="searchLocation">搜索</button>
				</view>
				<map 
					id="qqMap" 
					class="map"
					:longitude="longitude" 
					:latitude="latitude"
					:scale="scale"
					:markers="markers"
					@markertap="onMarkerTap"
					@tap="onMapTap"
				></map>
				<view class="map-footer">
					<button class="location-btn" @tap="getLocation">重新定位</button>
					<button class="confirm-btn" @tap="confirmLocation">确认位置</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { addressApi } from '../../api'
import { addressTypes, addressTypeValue } from '../../utils/address'
const QQMapWX = require('../../../static/js/qqmap-wx-jssdk.min.js')

// 表单数据
const form = ref({
	addressType: null, // 默认不选择
	isDefault: false//默认不选中
})

// 地图相关数据
const longitude = ref(113.943225)
const latitude = ref(22.543096)
const scale = ref(16)
const markers = ref([])
const qqmapsdk = ref(null)
const mapCtx = ref(null)
const showMap = ref(false)
const searchKeyword = ref('')

// 地区选择文本
const regionText = computed(() => {
	console.log("form.value:", form.value)
	if (form.value.province && form.value.city && form.value.district) {
		return form.value.province + form.value.city + form.value.district + (form.value.street || '')
	}
	return ''
})

onMounted(() => {
	qqmapsdk.value = new QQMapWX({
		key: 'SCGBZ-NEWY7-XNGX2-HCBAH-7UIRJ-OBF2X'
	})
	nextTick(() => {
		mapCtx.value = uni.createMapContext('qqMap')
	})
})

// 选择地区
const chooseRegion = () => {
	console.log('点击选择地区')
	showMap.value = true
	getLocation()
}

// 关闭地图弹窗
const closeMapPopup = () => {
	showMap.value = false
}

// 搜索位置
const searchLocation = () => {
	if (!searchKeyword.value) {
		uni.showToast({
			title: '请输入搜索关键词',
			icon: 'none'
		})
		return
	}
	
	qqmapsdk.value.search({
		keyword: searchKeyword.value,
		success: (res) => {
			if (res.data && res.data.length > 0) {
				const firstResult = res.data[0]
				longitude.value = firstResult.location.lng
				latitude.value = firstResult.location.lat
				
				markers.value = [{
					id: 0,
					longitude: firstResult.location.lng,
					latitude: firstResult.location.lat,
					title: firstResult.title,
					iconPath: '../../static/img/garbage/loc.png',
					width: 30,
					height: 30
				}]
				
				// 更新地址信息
				qqmapsdk.value.reverseGeocoder({
					location: {
						latitude: firstResult.location.lat,
						longitude: firstResult.location.lng
					},
					success: (addressRes) => {
						const address = addressRes.result
						form.value.province = address.address_component.province
						form.value.city = address.address_component.city
						form.value.district = address.address_component.district
						form.value.street = address.address_component.street
						form.value.detail = address.address_component.street_number
						
						// 移动地图到搜索位置
						if (mapCtx.value) {
							mapCtx.value.moveToLocation({
								latitude: firstResult.location.lat,
								longitude: firstResult.location.lng
							})
						}
					}
				})
			} else {
				uni.showToast({
					title: '未找到相关地址',
					icon: 'none'
				})
			}
		},
		fail: (err) => {
			console.error('搜索失败:', err)
			uni.showToast({
				title: '搜索失败',
				icon: 'none'
			})
		}
	})
}

// 获取当前位置
const getLocation = () => {
	uni.getLocation({
		type: 'gcj02',
		altitude: false,
		accuracy: 'best',
		success: (res) => {
			longitude.value = res.longitude
			latitude.value = res.latitude
			markers.value = [{
				id: 0,
				longitude: res.longitude,
				latitude: res.latitude,
				title: '当前位置',
				iconPath: '../../static/img/garbage/loc.png',
				width: 30,
				height: 30
			}]
			qqmapsdk.value.reverseGeocoder({
				location: {
					latitude: res.latitude,
					longitude: res.longitude
				},
				success: (addressRes) => {
					const address = addressRes.result
					console.log("获取当前位置时的地址信息:", address)
					
					// 更新表单数据
					form.value = {
						...form.value,
						province: address.address_component.province,
						city: address.address_component.city,
						district: address.address_component.district,
						street: address.address_component.street,
						detail: address.address_component.street_number || '',
						latitude: res.latitude,
						longitude: res.longitude,
						address: address.address // 完整地址
					}
					
					if (mapCtx.value) {
						mapCtx.value.moveToLocation({
							latitude: res.latitude,
							longitude: res.longitude
						})
					}
				},
				fail: (err) => {
					console.error('地址解析失败:', err)
					uni.showToast({
						title: '地址解析失败',
						icon: 'none'
					})
				}
			})
		},
		fail: (err) => {
			console.error('获取位置失败:', err)
			if (err.errMsg && err.errMsg.includes('auth deny')) {
				uni.showModal({
					content: '需要位置权限才能使用此功能',
					success: (modalRes) => {
						if (modalRes.confirm) {
							uni.openSetting()
						}
					}
				})
			} else if (err.errMsg && err.errMsg.includes('ERROR_NOCELL&WIFI_LOCATIONSWITCHOFF')) {
				uni.showModal({
					content: '请开启手机定位服务',
					showCancel: false
				})
			}
		}
	})
}

// 地图点击事件
const onMapTap = (e) => {
	const { latitude: lat, longitude: lng } = e.detail
	latitude.value = lat
	longitude.value = lng
	
	markers.value = [{
		id: 0,
		longitude: lng,
		latitude: lat,
		title: '选中位置',
		iconPath: '../../static/img/garbage/loc.png',
		width: 30,
		height: 30
	}]
	
	// 获取地址信息
	qqmapsdk.value.reverseGeocoder({
		location: {
			latitude: lat,
			longitude: lng
		},
		success: (addressRes) => {
			const address = addressRes.result
			console.log("点击地图时的地址信息:", address)
			
			// 更新表单数据
			form.value = {
				...form.value,
				province: address.address_component.province,
				city: address.address_component.city,
				district: address.address_component.district,
				street: address.address_component.street,
				detail: address.address_component.street_number || '',
				latitude: lat,
				longitude: lng,
				address: address.address // 完整地址
			}
		}
	})
}

// 确认位置
const confirmLocation = () => {
	// 再次获取地址信息确保数据完整
	qqmapsdk.value.reverseGeocoder({
		location: {
			latitude: latitude.value,
			longitude: longitude.value
		},
		success: (addressRes) => {
			const address = addressRes.result
			console.log("确认位置时的地址信息:", address)
			
			// 更新表单数据
			form.value = {
				...form.value,
				province: address.address_component.province,
				city: address.address_component.city,
				district: address.address_component.district,
				street: address.address_component.street,
				detail: address.address_component.street_number || '',
				latitude: latitude.value,
				longitude: longitude.value,
				address: address.address // 完整地址
			}
			
			// 关闭地图弹窗
			closeMapPopup()
			
			// 提示用户
			uni.showToast({
				title: '位置已选择',
				icon: 'success'
			})
		},
		fail: (err) => {
			console.error('获取地址信息失败:', err)
			uni.showToast({
				title: '获取地址信息失败',
				icon: 'none'
			})
		}
	})
}

// 获取单条地址
const getAddressDetail = async (addressId) => {
	console.log("addressId:", addressId)
	const res = await addressApi.getAddressDetail(addressId)
	console.log("res:", res)
	if (res.code === 200) {
		const data = {
			...res.data
		}
		// 只有当addressType有值时才赋值
		if (res.data.addressType) {
			data.addressType = addressTypeValue(res.data.addressType)
		}
		Object.assign(form.value, data)
	}
	else{
		uni.showToast({
			title: res.msg,
			icon: 'none'
		})
	}
}

// 预留接口：保存地址
const saveAddress = async () => {
	// 表单校验
	if (!form.value.contacts) {
		uni.showToast({ title: '请填写收货人姓名', icon: 'none' }); return
	}
	if (!/^1[3-9]\d{9}$/.test(form.value.contactsPhone)) {
		uni.showToast({ title: '请填写正确手机号', icon: 'none' }); return
	}
	if (!form.value.province || !form.value.city || !form.value.district) {
		uni.showToast({ title: '请选择省市区', icon: 'none' }); return
	}
	if (!form.value.detail) {
		uni.showToast({ title: '请填写详细地址', icon: 'none' }); return
	}
	
	try {
		form.value.uId = uni.getStorageSync('token')
		console.log("form.value:", form.value)
		const res = await addressApi.saveAddress(form.value)
		console.log("res:", res)
		
		if (res && res.code === 200) {
			// 发送刷新事件
			uni.$emit('refreshAddressList')
			uni.showToast({ title: '保存成功', icon: 'success' })
			uni.navigateBack()
		} else {
			uni.showToast({ 
				title: res?.msg || '保存失败', 
				icon: 'none' 
			})
		}
	} catch (error) {
		console.error('保存地址失败:', error)
		uni.showToast({ 
			title: '保存失败，请稍后重试', 
			icon: 'none' 
		})
	}
}

// 地址类型改变事件
const onAddressTypeChange = (e) => {
	form.value.addressType = e.detail.value === null ? null : Number(e.detail.value)
}

// 监听页面参数，判断是新增还是编辑
onLoad((query) => {
	console.log("query:", query)
	if (query.addressId && query.addressId !== '0') {
		getAddressDetail(query.addressId)
	}
})
</script>

<style lang="scss" scoped>
.address-edit-page {
	min-height: 100vh;
	background: #f5f5f5;
	padding-bottom: 100rpx;
}
.form-card {
	background: #fff;
	border-radius: 18rpx;
	margin: 32rpx 24rpx 0 24rpx;
	box-shadow: 0 2rpx 12rpx rgba(44, 62, 80, 0.04);
	padding: 0 0 0 0;
}
.form-row {
	display: flex;
	align-items: center;
	border-bottom: 1rpx solid #f0f0f0;
	padding: 0 24rpx;
	height: 90rpx;
	&:last-child { border-bottom: none; }
}
.form-label {
	width: 140rpx;
	color: #222;
	font-size: 28rpx;
}
.form-input {
	flex: 1;
	font-size: 28rpx;
	color: #333;
	border: none;
	background: transparent;
	outline: none;
}
.form-picker {
	flex: 1;
	height: 90rpx;
	display: flex;
	align-items: center;
}
.picker-text {
	font-size: 28rpx;
	color: #333;
}
.default-card {
	background: #fff;
	border-radius: 18rpx;
	margin: 24rpx 24rpx 0 24rpx;
	box-shadow: 0 2rpx 12rpx rgba(44, 62, 80, 0.04);
	padding: 0 0 0 0;
}
.default-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 90rpx;
	padding: 0 24rpx;
}
.default-label {
	color: #222;
	font-size: 28rpx;
}
.default-switch {
	transform: scale(0.8);
}
.default-tip {
	color: #bbb;
	font-size: 22rpx;
	padding: 0 24rpx 18rpx 24rpx;
}
.save-btn-box {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 24rpx;
	background: #f5f5f5;
	z-index: 10;
	display: flex;
	justify-content: center;
	padding-bottom: env(safe-area-inset-bottom);
}
.save-btn {
	width: 90vw;
	max-width: 700rpx;
	background: #2196f3;
	color: #fff;
	font-size: 28rpx;
	border-radius: 40rpx;
	border: none;
	height: 80rpx;
	line-height: 80rpx;
	font-weight: 500;
	box-shadow: none;
	margin: 0 auto;
	display: flex;
	align-items: center;
	justify-content: center;
}

.map-popup {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	background: #fff;
	z-index: 999;
	border-radius: 24rpx 24rpx 0 0;
	box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.map-container {
	height: 80vh;
	display: flex;
	flex-direction: column;
}

.map-header {
	padding: 24rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 1rpx solid #eee;
	
	.close-btn {
		font-size: 40rpx;
		color: #999;
		padding: 0 20rpx;
	}
}

.map {
	flex: 1;
	width: 100%;
}

.map-footer {
	padding: 24rpx;
	display: flex;
	gap: 24rpx;
	
	button {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 28rpx;
		border-radius: 40rpx;
	}
	
	.location-btn {
		background: #f5f5f5;
		color: #666;
	}
	
	.confirm-btn {
		background: #2196f3;
		color: #fff;
	}
}

.search-box {
	padding: 20rpx 24rpx;
	display: flex;
	gap: 20rpx;
	background: #fff;
	border-bottom: 1rpx solid #eee;
	
	.search-input {
		flex: 1;
		height: 72rpx;
		background: #f5f5f5;
		border-radius: 36rpx;
		padding: 0 30rpx;
		font-size: 28rpx;
	}
	
	.search-btn {
		width: 120rpx;
		height: 72rpx;
		line-height: 72rpx;
		background: #2196f3;
		color: #fff;
		font-size: 28rpx;
		border-radius: 36rpx;
		padding: 0;
	}
}
</style>
